package cdc.rxjava2.demo;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableEmitter;
import io.reactivex.FlowableOnSubscribe;

public class Hello1 {
	/**
	 * create a flowable Publisher:出版者;
	 * 
	 * subscribe:订阅
	 * 
	 * 平常用得最多的Publisher是Flowable
	 * 
	 **/
	private Flowable<String> flowable = Flowable.create(new FlowableOnSubscribe<String>() {
		@Override
		public void subscribe(FlowableEmitter<String> e) throws Exception {
			e.onNext("RxJava2  Hello1");
			e.onComplete();
		}
	}, BackpressureStrategy.BUFFER);

	/**
	 * subscriber 订阅者
	 * 
	 * Subscription:订阅
	 **/
	private Subscriber<String> subscriber = new Subscriber<String>() {

		/**
		 * 在onSubscribe中，我们需要调用request去请求资源， 参数就是要请求的数量，一般如果不限制请求数量， 可以写成Long.MAX_VALUE。
		 * 如果你不调用request，Subscriber的onNext和onComplete方法将不会被调用。
		 * 
		 * 
		 */
		@Override
		public void onSubscribe(Subscription s) {
			System.out.println("===订阅者onSubscribe===");
			s.request(Long.MAX_VALUE);
		}

		/**
		 * onNext方法里面传入的参数就是Flowable中发射出来的。
		 * 
		 **/
		@Override
		public void onNext(String s) {
			System.out.println(s);
		}

		@Override
		public void onError(Throwable t) {

		}

		@Override
		public void onComplete() {
			System.out.println("===订阅者onComplete===");
		}
	};
	
	public Hello1() {
		flowable.subscribe(subscriber);
	}

}
